import {iIndexData, iIndexDataPublic, iMicroConfig} from "@peryl/micro-web";
import {computed, inject, onBeforeUnmount, provide, reactive, watch} from "@peryl/react-compose";
import {createEffects} from "@peryl/utils/createEffects";
import {remove} from "@peryl/utils/remove";

/**
 * 为了避免 web base的navigator遮住子应用frameMode为frame的组件弹窗，这里控制当展示的子应用为frameMode:frame时，app-content节点的z-index为7，大于app-navigator；令 [data-micro-container]:not([data-micro-frame-mode-none])的节点的top为 app-header；
 * @author  韦胜健
 * @date    2024.6.29 21:00
 */
export const useCurrentMicroConfig = (() => {

  const PROVIDE_NAME = '@@useCurrentMicroConfig';

  const _provide = () => {
    const state = reactive({
      list: [] as iIndexDataPublic[],
      current: computed((): undefined | null | iIndexDataPublic => state.list[0])
    });

    const refer = {
      state,
    };

    provide(PROVIDE_NAME, refer);

    return refer;
  };

  const _inject = (
    {
      props, getIndexData,
    }: {
      props: { active: boolean, microConfig: iMicroConfig },
      getIndexData: () => iIndexData | undefined | null,
    }
  ) => {

    const injection = inject<ReturnType<typeof _provide> | null>(PROVIDE_NAME, null);
    if (!injection) {return;}

    const { effects } = createEffects();

    const unwatch = watch((): boolean => props.active && !!getIndexData(), (flag, oldFlag) => {
      if (flag == oldFlag && oldFlag != null) {return;}
      const indexData = getIndexData();
      effects.clear();
      if (!(!flag || !indexData)) {
        injection.state.list.push(indexData);
        effects.push(() => remove(injection.state.list, indexData));
      }
    });

    onBeforeUnmount(() => {
      unwatch();
      effects.clear();
    });

  };

  return {
    provide: _provide,
    inject: _inject,
  };

})();
